package com.atguigu.juc.date928;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: shenhao
 * @CreatTime: 2024/9/28 22:16
 * @Version: 1.0
 * arraylist线程不安全的例子
 */
public class NoSafeArrayList {
    //证明集合不安全
    public static void main(String[] args) {
        // Vector效率很低, 不能使用
        //读写分离+写时复制
        //notSalfArrayList();
        //noSafeSet();
        notSafeHashMap();
    }

    private static void notSafeHashMap() {
        Map<String,String> map =new ConcurrentHashMap<>(); //Collections.synchronizedList(new ArrayList<>());//new Vector<>(); //new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Thread t=new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,8));
                System.out.println(map);
            },String.valueOf(i));
            t.start();
        }
    }

    private static void noSafeSet() {
        Set<String> set =new CopyOnWriteArraySet<>(); //Collections.synchronizedSet(new ArrayList<>()); //new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Thread t=new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            },String.valueOf(i));
            t.start();
        }
    }

    private static void notSalfArrayList() {
        List<String> list =new CopyOnWriteArrayList<>(); //Collections.synchronizedList(new ArrayList<>());//new Vector<>(); //new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Thread t=new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(list);
            },String.valueOf(i));
            t.start();
        }
    }
}
